# coding:utf-8
from odoo import models, fields, api, _
from odoo.exceptions import Warning


class PaulStockPickingExtend(models.Model):
    _name = 'stock.picking'
    _inherit = 'stock.picking'

    @api.model
    def create(self, vals):
        so = self.env['sale.order'].search([('name', '=', vals['origin'])])
        vals['note'] = so.note
        return super(PaulStockPickingExtend, self).create(vals)

    @api.multi
    def check_proportion(self):
        for line in self.pack_operation_product_ids:
            # calculate order's sum qty
            order_product_qty = 0
            proportion = 0
            # calculate already trans qty, and calc returned qty in sale order line
            picking_done_qty = 0
            # add return qty at req280
            qty_returned = 0
            for ol in self.sale_id.order_line:
                if line.product_id == ol.product_id:
                    order_product_qty += ol.product_uom_qty
                    proportion = ol.proportion
                    qty_returned = ol.qty_returned
                    break
            # find all transfer in same order
            for picking in self.sale_id.picking_ids:
                if picking.state == 'done' and not picking.return_reason:
                    for pl in picking.pack_operation_product_ids:
                        if line.product_id == pl.product_id:
                            picking_done_qty += pl.qty_done
            # can_out_qty = round((order_product_qty - picking_done_qty + qty_returned) * (100 + line.product_id.product_tmpl_id.permissible_proportion) * 0.01, 0)
            can_out_qty = round((order_product_qty * (100 + line.product_id.product_tmpl_id.permissible_proportion)*0.01 - picking_done_qty + qty_returned ) , 0)
            if not line.picking_id.return_reason and line.qty_done > can_out_qty:
                out_qty = line.qty_done - can_out_qty
                raise Warning(u'商品'+line.product_id.name+u'调拨数量超出允出数量,超出数量为:'+str(out_qty))
        return super(PaulStockPickingExtend, self).do_new_transfer()
